/**
 * Created by wyy on 17-7-10.
 */
angular.module('tribalc').service('Api', ['$http', '$state', 'Alert', function ($http, $state, Alert) {
    var status = "debug";
    var CLIENT_BASE_URL = "/tribalc/v1.0";

    if (status === 'debug') {
        CLIENT_BASE_URL = "https://dev-app-services.buluo-gs.com/tribalc/v1.0";
        // CLIENT_BASE_URL = "https://app-services.buluo-gs.com/tribalc/v1.0";
        // CLIENT_BASE_URL = "https://localhost:8080/tribalc/v1.0";
    }

    var ALIYUN_URL = "https://buluo-gs-pictures.oss-cn-beijing.aliyuncs.com/";

    var assigned = function () {
        return window.localStorage.assign;

    };
    var headers = function () {
        return {
            "Content-Type": "application/json",
            "Accept": "application/json",
            "Authorization": localStorage.token
        };
    };
    var http = function (url, method, data, sucFuc, errFuc, notNeedLogin) {
        var req = {
            url: CLIENT_BASE_URL + '/' + url,
            method: method.toUpperCase(),
            headers: headers(),
            data: null
        };
        if ((arguments[1].toUpperCase() === 'POST' || arguments[1].toUpperCase() === 'PUT')) {
            req.data = data;
        } else {
            var temp = sucFuc;
            sucFuc = data;
            errFuc = temp;
        }
        $http(req)
            .then(function successCallback(response) {
                    sucFuc(response.data);
                },
                function errorCallback(response) {
                    if (response.status == 401) {
                        return gotoLogin();
                    }
                    errFuc ? errFuc(response) : '';
                }
            );

    };

    function gotoLogin() {

        localStorage.clear();

        Alert.alertBox('您的账号在其他地方登陆，请重新登录');
        $state.go('login');

    }


    // 公司资源
    function login(phone, password, sucFuc, errFuc) {
        var path = "companies/" + "login";
        var data = {
            "phone": phone,
            "password": password
        };
        http(path, 'post', data, function (result) {
            if (result.code === 200) {

                sucFuc(result);

            } else if (result.code === 400) {
                Alert.alertBox('用户名或密码错误');
            } else {
                Alert.alertBox('登录失败, ' + result.message | '');
            }
        }, function (error) {
            Alert.alertBox('登录失败, 服务器错误');
            errFuc ? errFuc(error) : '';
        }, true)
    }


    //获取企业信息
    function getCompanyDetail(id, sucFuc, errFuc) {
        var companyId = id ? id : window.localStorage.assign;
        var path = "companies/" + companyId;

        http(path, 'get', function (result) {
            if (result.code === 200) {

                sucFuc(result);
            } else if (result.code === 404) {
                Alert.alertBox('获取公司信息失败, 没有找到该公司');
            }
        }, function (error) {
            Alert.alertBox('获取公司信息失败, 服务器错误');
            errFuc ? errFuc(error) : '';
        });
    }
    //获取房源列表
    function getApartmentList(communityId,pageNum,pageSize,sucFun,errFun) {
        // pageNum=pageNum ===null ? "": "&pageNum=" + pageNum;
        // pageSize=pageSize===null ?"": "&pageSize"+pageSize
        var path = "apartments?me="+assigned()+"&communityId="+communityId+"&type=company"+'&pageNum='+pageNum+'&pageSize='+pageSize;
        http(path,'get',function (result) {
            if (result.code ===200)
            {
                sucFun(result);
            }else if(result.code === 403){
                Alert.alertBox('无查看权限')
            }
        });
    }


    //获取房源信息
    function getApartmentListInfo(communityId,apartmentId,sucFun,errFun) {
        var path ="apartments/"+apartmentId+"?me="+assigned()+"&communityId="+communityId+"&type=company";
        http(path,'get',function (result) {
            if (result.code === 200)
            {
                sucFun(result);

            }
            else if(result.code === 403){
                Alert.alertBox('无查看权限')
            }

        });
    }

    //删除房源信息
    function deleteApartmentInfo(apartmentId,sucFun) {
        var path="apartments/"+apartmentId+"?me=" + assigned();
        var message = '';

        http(path,'delete',function (result) {

            if (result.code === 204) {
                sucFun(result);
                // Alert.alertBox(message + ',房源信息删除成功！');
            }
            else if(result.code === 403){
                Alert.alertBox(message + ',房源已入住，不允许删除房源！');

            }
        });

    }

    //增加房源信息
    function addApartmentInfo(apartmentInfoModel,id,sucFuc) {
        var data=apartmentInfoModel.getObject();
        console.log(data);

        var path="apartments?me="+id;
        console.log(path)
        http(path,'post',data,function (result) {
            console.log(result);
            if(result.code === 201)
            {
                sucFuc(result);

            }else if(result.code === 507)
            {
                Alert.alertBox('房源提交失败，请重新提交！')
            }
        });


    }
    // objectkey和putUrl参数根据上传图片接口获得
    function callAliyunPicture(objectkey, putUrl, file, sucFuc) {
        putUrl = 'https' + putUrl.substring(putUrl.indexOf('://'));
        var imageUrl = ALIYUN_URL + objectkey;
        var xhr = new XMLHttpRequest();
        xhr.open('PUT', putUrl, true);
        xhr.setRequestHeader("Content-Type", "image/jpeg");
        xhr.onload = function () {
            if (xhr.status == 200) {
                sucFuc(imageUrl);
            } else {
                Alert.alertBox('图片上传失败');
            }
        };
        xhr.send(file);
    }

    //获取城市
    function getChinaCitysJson(sucFuc) {
        $http({
            url: '/tribalc-web-apartment/json/chinaCityInfo.json'
        }).then(function (result) {
            sucFuc(result.data);
        }, function (error) {

        });
    }

    //上传图片
    function uploadPicture(contentMD5, id,sucFuc, errFuc) {
        var picName = Date.parse(new Date())+"web_image.jpg";
        var path = "oss_authorization/picture?me=" + id;
        var data = {
            key: picName,
            contentType: 'image/jpeg',
            contentMD5: contentMD5
        };
        http(path, 'post', data, function (result) {
            sucFuc(result);
        }, function (error) {
            alert('error');
        });
    }

    //修改房源信息

    function perfectApartmentInfo(apartmentData,sucFun) {
        var data = apartmentData.getObject();
        console.log(data)
        var keyPath = "";
        // if (data.pictures.length != 0) amendData.pictures = data.pictures;
        delete data['community'];
        Object.keys(data).forEach(function (key, index) {
            if (key != 'id' && key != 'communityId' && key != 'community')
            {
                if (keyPath == '') {
                    keyPath += key;
                } else{
                    keyPath += "," + key;
                }
            }

        });
        var path = 'apartments/'+apartmentData.id+"/"+keyPath+'?me=' + assigned();
        console.log(data);
        console.log(path);
        http(path,'put',data,function (result) {
            console.log(result);
            if(result.code === 200){
                sucFun(result);
            }else if(result.code === 507){
                Alert.alertBox('房源信息修改失败，请重新提交！')
            }
        });

    }

    //获取社区信息
    function getCommunityList(sucFuc, errFuc) {
        http('communities', 'get', function (result) {
            if (result.code == 200) {
                sucFuc(result);
            } else {
                Alert.alertBox('获取社区列表失败，失败原因：' + result.message);
            }
        }, function (error) {
            Alert.alertBox('获取社区列表失败,服务器错误');
            errFuc ? errFuc(error) : '';
        })
    }
    //创建租客协议
    function createRentProtocol(rentProtocolModel,sucFuc,errFuc) {
        // console.log(rentProtocolModel);
        var data = rentProtocolModel.getCreateObject();
        var path = 'rent_protocols?me=' + assigned();
        http(path,'post',data,function (result) {
            console.log(data)
            if (result.code == 201) {
                sucFuc(result);
            } else if (result.code == 400) {
                Alert.alertBox('创建缴租合同失败,请检查输入内容');
            } else if (result.code == 403) {
                Alert.alertBox('创建缴租合同失败,无操作权限');
            } else {
                Alert.alertBox('创建缴租合同失败' + result.message);
            }
        })
    }

    function getRentlistInfo(sourceId,sucFun) {
        // var data = rentProtocolModel.getCreateObject()
        var path = 'rent_protocols/'+'actived'+'?me='+assigned()+'&sourceId='+sourceId;
        http(path,"get",function (result) {
            if (result.code === 200){
                sucFun(result)
            }
            else if (result.code === 403){
                Alert.alertBox('无操作权限')
            }
        })
    }

    function getRentpaymentInfo(id,sucFuc,errfuc) {
        console.log(id)
        var path = 'rent_protocols/'+id+'/plan_items'+'?me='+ assigned() + '&fetchAll=true';
        http(path,'get',function (result) {
            if(result.code === 200){
                sucFuc(result);
            }
            else if(result.code === 404)
            {
                Alert.alertBox('找不到该租赁协议');
            } else if(result.code === 403)
            {
                Alert.alertBox('无操作权限');
            }
        });
    }

    function creatLock(lockModel,sucFun) {
        var data = lockModel.getObject();
        path = 'smart_locks?me='+ assigned();
        http(path,'post',data,function (result) {
            if(result.code===201){
                sucFun(result);
            }else if(result.code === 403){
                Alert.alertBox('无创建权限!')
            }
        })
    }

    function getLcokInfo(sourceId,sn,sucFun) {
        var path = 'smart_locks/'+'status'+'?me='+assigned()+'&sourceId='+sourceId+'&sn='+sn;

        http(path,'get',function (result) {
            console.log(result)
            if(result.code === 200){
                sucFun(result)
            }else if(result.code === 403){
                Alert.alertBox('无权限操作')
            }else if(result.code === 507){
                Alert.alertBox('创建失败')
            }
        })
    }

    function getLockInfoList(sourceId,sucFun) {
        var path = 'smart_locks?me='+assigned()+'&sourceId='+sourceId
        http(path,'get',function (result) {
            if (result.code===200 || result.code == 404){
                sucFun(result)
            }
        })
    }

    function changeApartmentStatus(apartmentId,data,sucFun){
        var path = 'apartments/'+apartmentId + '/status?me='+assigned();
        console.log(path)
        http(path,'put',data,function (result) {
            if (result.code === 200){
                sucFun(result)
            }else if(result.code === 403){
                Alert.alertBox('无权限修改房源状态')
            }else if(result.code === 507){
                Alert.alertBox('房源信息修改失败，请重新提交！')
            }else {
                Alert.alertBox('网络错误')
            }
        },function(){

        })
    }
    
    function getRentprotocolInfo(id,sucFun) {
        var path = 'rent_protocols/'+id+'/withhold?me='+assigned();
        http(path,'get',function (result) {
            if(result.code===200){
                sucFun(result);
            }else if(result.code===404){
                Alert.alertBox('协议不存在');
            }
        });
    }
    function cancleRentprotocol(id,rentName,sucFun) {
        var path = 'rent_protocols/'+ id +'?me='+assigned() + '&ownerName='+ rentName;
        console.log(path)
        http(path,'delete',function (result) {
            console.log(result)
            if(result.code === 204){
                sucFun(result)
            }else if(result.code === 400){
                Alert.alertBox('确认名称输入错误');
            }else if(result.code === 404){
                console.log(result)
                Alert.alertBox('找不到该租赁协议');
            }else if(result.code === 403){
                Alert.alertBox('无操作权限');
            }else if(result.code === 409){
                Alert.alertBox('协议状态冲突');
            }else if(result.code === 507){
                Alert.alertBox('删除失败');
            }
        })
    }

    // 公司资源

    /**
     * 登录
     * @param phone 帐号/手机号
     * @param password 密码
     * @param sucFuc
     * @param errFuc
     * */

    this.login = login;
    // 工具
    this.getAssign = assigned;
    this.CLIENT_BASE_URL = CLIENT_BASE_URL;
    this.ALIYUN_URL = ALIYUN_URL;
    //获取房源
    this.getApartmentList = getApartmentList;
    this.getCompanyDetail = getCompanyDetail;
    this.getApartmentListInfo=getApartmentListInfo;

    this.deleteApartmentInfo=deleteApartmentInfo;
    this.changeApartmentStatus = changeApartmentStatus;

    this.addApartmentInfo = addApartmentInfo;

    this.perfectApartmentInfo = perfectApartmentInfo

    /**
     * 阿里云图片上传
     * */
    this.callAliyunPicture = callAliyunPicture;

    this.getChinaCitysJson= getChinaCitysJson;

    this.uploadPicture=uploadPicture;
    this.getCommunityList = getCommunityList;
    this.createRentProtocol = createRentProtocol;

    this.getRentlistInfo = getRentlistInfo;

    this.getRentpaymentInfo = getRentpaymentInfo;
    this.creatLock =creatLock;
    this.getLcokInfo=getLcokInfo;
    this.getLockInfoList=getLockInfoList;

    this.getRentprotocolInfo=getRentprotocolInfo;
    this.cancleRentprotocol = cancleRentprotocol;
}]);